<template>
  <el-main>
    <el-tabs type="border-card">
      <el-tab-pane label="用户信息">
        <el-row :gutter="20">
          <el-col :span="12" :xs="24">
            <el-form
              ref="entityForm"
              :model="entityModel"
              :rules="entityRules"
              label-width="100px"
            >
              <el-row>
                <el-form-item prop="avatar" label="用户头像" class="avatar-item">
                  <userAvatar style="margin-left: -100px" />
                </el-form-item>
                <el-form-item prop="username" label="用户名称">
                  <el-input v-model="entityModel.username" placeholder="请输入用户名称" readonly disabled />
                </el-form-item>
                <el-form-item prop="sex" label="用户性别">
                  <el-select v-model="entityModel.sex" placeholder="请输入用户性别">
                    <el-option label="男" :value="0" />
                    <el-option label="女" :value="1" />
                  </el-select>
                </el-form-item>
                <el-form-item prop="phone" label="用户手机">
                  <el-input v-model="entityModel.phone" placeholder="请输入用户手机" />
                </el-form-item>
                <el-form-item prop="email" label="用户邮箱">
                  <el-input v-model="entityModel.email" placeholder="请输入用户邮箱" />
                </el-form-item>
                <el-form-item v-if="deptName !== null" prop="deptId" label="所属部门">
                  <el-input v-model="deptName" placeholder="请输入所属部门" readonly disabled />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="updateHandler()">更新信息</el-button>
                </el-form-item>
              </el-row>
            </el-form>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="修改密码">
        <el-row :gutter="20">
          <el-col :span="12" :xs="24">
            <el-form
              ref="passwordForm"
              :model="passwordModel"
              :rules="passwordRules"
              label-width="100px"
            >
              <el-row>
                <el-form-item prop="oldPassword" label="旧密码">
                  <el-input v-model="passwordModel.oldPassword" type="password" placeholder="请输入旧密码" />
                </el-form-item>
                <el-form-item prop="newPassword" label="新密码">
                  <el-input v-model="passwordModel.newPassword" type="password" placeholder="请输入新密码" />
                </el-form-item>
                <el-form-item prop="againPassword" label="确认密码">
                  <el-input v-model="passwordModel.againPassword" type="password" placeholder="请输入新密码" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="changePassword()">更新密码</el-button>
                </el-form-item>
              </el-row>
            </el-form>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>
  </el-main>
</template>

<script>
import { mapGetters } from 'vuex'
import userAvatar from './avatar'
import { validPassword, validPhone, validEmail } from '@/utils/validate'
import { getById as getDeptById } from '@/api/sysDepartment'
import { getByUsername, update, changePassword } from '@/api/sysUser'
export default {
  name: 'Profile',
  components: { userAvatar },
  props: {},
  data() {
    const validatePassword = (rule, value, callback) => {
      if (!validPassword(value)) {
        callback(new Error('4-20位，可字母、数字、下划线'))
      } else {
        callback()
      }
    }
    const validatePhone = (rule, value, callback) => {
      if (!validPhone(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }
    const validateEmail = (rule, value, callback) => {
      if (!validEmail(value)) {
        callback(new Error('请输入正确的邮箱号'))
      } else {
        callback()
      }
    }
    const validateAgainPassword = (rule, value, callback) => {
      const np = this.passwordModel.newPassword
      const ap = this.passwordModel.againPassword
      if (np === null || ap === null || np === '' || ap === '' || np !== ap) {
        callback(new Error('两次密码输入不一致！'))
      } else {
        callback()
      }
    }
    return {
      entityModel: {
        id: null,
        username: null,
        password: null,
        avatar: null,
        sex: 0,
        phone: null,
        email: null,
        state: 0,
        deptId: null
      },
      entityRules: {
        phone: [{ required: true, trigger: 'blur', validator: validatePhone }],
        email: [{ required: true, trigger: 'blur', validator: validateEmail }]
      },
      passwordModel: {
        username: null,
        newPassword: null,
        oldPassword: null,
        againPassword: null
      },
      passwordRules: {
        newPassword: [{ required: true, trigger: 'blur', validator: validatePassword }],
        oldPassword: [{ required: true, trigger: 'blur', validator: validatePassword }],
        againPassword: [{ required: true, trigger: 'blur', validator: validateAgainPassword }]
      },
      deptName: null
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'avatar'
    ])
  },
  created() {
    this.loadUserInfo()
  },
  methods: {
    loadUserInfo() {
      getByUsername({ 'username': this.name }).then((response) => {
        if (response.code === 200) {
          this.entityModel = response.data
          this.loadDeptName()
        }
      })
    },
    loadDeptName() {
      getDeptById({ 'id': this.entityModel.deptId }).then((response) => {
        if (response.code === 200) {
          if (response.data) {
            this.deptName = response.data.name
          }
        }
      })
    },
    updateHandler() {
      this.$refs.entityForm.validate(valid => {
        if (valid) {
          this.entityModel.avatar = this.avatar
          update(this.entityModel).then((response) => {
            if (response.code === 200) {
              this.$notify.success({ title: '系统提示', message: response.msg })
            }
          })
        }
      })
    },
    changePassword() {
      this.$refs.passwordForm.validate(valid => {
        if (valid) {
          this.passwordModel.username = this.name
          changePassword(this.passwordModel).then((response) => {
            if (response.code === 200) {
              this.$notify.success({ title: '系统提示', message: response.msg })
              this.logout()
            }
          })
        }
      })
    },
    async logout() {
      await this.$store.dispatch('user/logout')
      this.$router.push(`/login?redirect=${this.$route.fullPath}`)
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar-item {
  display: flex;
  align-items: center;
}
</style>
